package cn.xxstudy.permission.help.task

import cn.xxstudy.permission.help.PermissionBuilder
import cn.xxstudy.permission.help.PermissionHelper

/**
 * @author ：wuxinxi on 2020/11/10 .
 * @packages ：cn.xxstudy.permission.help.chain .
 * TODO:权限任务
 */
class PermissionTask(private val permissionBuilder: PermissionBuilder) : ITask {
    override fun request() {
        //重新过滤一下权限申请状态
        val requestPermissionList = mutableListOf<String>()
        for (permission in permissionBuilder.permissions) {
            if (PermissionHelper.isGranted(permissionBuilder.activity, permission)) {
                permissionBuilder.grantedPermissions.add(permission)
            } else {
                requestPermissionList.add(permission)
            }
        }
        if (requestPermissionList.size == 0) {
            permissionBuilder.permissionResultCallback?.callback(
                true,
                permissionBuilder.grantedPermissions.toTypedArray(),
                emptyArray(),
                emptyArray()
            )
            return
        }
        permissionBuilder.getPermissionFragment().request(permissionBuilder, requestPermissionList.toTypedArray())
    }

    override fun requestSettings() {
        permissionBuilder.jumpSettings()
    }

    override fun retryRequest() {
        val requestPermissionList = mutableListOf<String>()
        for (permission in permissionBuilder.permissions) {
            if (PermissionHelper.isGranted(permissionBuilder.activity, permission)) {
                permissionBuilder.grantedPermissions.add(permission)
            } else {
                requestPermissionList.add(permission)
            }
        }
        permissionBuilder.getPermissionFragment()
            .request(permissionBuilder, requestPermissionList.toTypedArray())
    }
}